import { createStore } from 'vuex';
import axios from 'axios';

const store = createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || ''
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    },
    setToken(state, token) {
      state.token = token;
    }
  },
  actions: {
    async login({ commit }, credentials) {
      const response = await axios.post('http://localhost:8080/api/users/login', credentials);
      const token = response.data.token;
      localStorage.setItem('token', token);
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      commit('setToken', token);
      commit('setUser', response.data.user);
    },
    async register({ commit }, userData) {
      await axios.post('http://localhost:8080/api/users/register', userData);
    },
    async fetchUser({ commit }) {
      const response = await axios.get('http://localhost:8080/api/users/me');
      commit('setUser', response.data);
    },
    logout({ commit }) {
      localStorage.removeItem('token');
      delete axios.defaults.headers.common['Authorization'];
      commit('setUser', null);
      commit('setToken', '');
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    user: state => state.user
  }
});

export default store;